package com.bdqn.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.bdqn.entity.User;


public class ExcelUtil {
	
	
	public static void saveExcel(List<User> userList) throws FileNotFoundException {
		// 创建一个空白excel
		HSSFWorkbook workbook = new HSSFWorkbook();

		// 在excel上创建一页
		HSSFSheet sheet = workbook.createSheet("用户信息");

		// 获取页上的第一行
		HSSFRow row = sheet.createRow(0);

		// 获取第一行的第一格
		HSSFCell cell = row.createCell(0);
		cell.setCellValue("id");
		HSSFCellStyle style = workbook.createCellStyle();
		
		
		cell.setCellStyle(style);

		// 获取第一行的第二格
		cell = row.createCell(1);
		cell.setCellValue("usercode");

		// 获取第一行的第三格
		cell = row.createCell(2);
		cell.setCellValue("username");

		// 获取第一行的第四格
		cell = row.createCell(3);
		cell.setCellValue("tel");

		// 获取第一行的第五格
		cell = row.createCell(4);
		cell.setCellValue("gender");

		for (int i = 0; i < userList.size(); i++) {
			row = sheet.createRow(i + 1);
			
			cell = row.createCell(0);
			cell.setCellValue(userList.get(i).getId());

			// 获取第一行的第二格
			cell = row.createCell(1);
			cell.setCellValue(userList.get(i).getUserCode());

			// 获取第一行的第三格
			cell = row.createCell(2);
			cell.setCellValue(userList.get(i).getUserName());

			// 获取第一行的第四格
			cell = row.createCell(3);
			cell.setCellValue(userList.get(i).getPhone());

			// 获取第一行的第五格
			cell = row.createCell(4);
			cell.setCellValue(userList.get(i).getGender());
		}
		
		FileOutputStream fos = new FileOutputStream(new File("D:\\用户信息.xls"));
		
		try {
			workbook.write(fos);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			if(fos!=null)
			try {
				fos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
